﻿using System;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using System.IO;
using System.Net;

namespace CoreMotivesWebPart
{
	/// <summary>
	/// Because the HTTP request seems to hold up the loading of pages in SharePoint, which severly
	/// impacts website performance we spin the HTTP request off into it's own thread that will
	/// complete the request (or fail) and gracefully terminate, independent of the calling web page.
	/// </summary>
	public class CMLoggingWorker
	{
		private Boolean _ignoreCertificateErrors;

		public String CoreMotivesRequestUri { get; set; }
		public String UserAgent { get; set; }
		public String Parameters { get; set; }
		public CMLoggingWorker(Boolean ignoreCertificateErrors)
		{
			_ignoreCertificateErrors = ignoreCertificateErrors;
		}

		public void LogPageRequest()
		{
			try
			{
				if (_ignoreCertificateErrors)
				{
					// this line added to accept any certificate. In development it was speculated that certain network monitoring
					// devices were causeing intermittent SSL/Certificate errors while trying to submit data to CoreMotives.
					// this line has been added to overcome that. It is only activated if the administrator/developer has
					// enabled IgnoreCertificateError in configuration.
					// A more elegant solution would be preferred.
					ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
				}

				HttpWebRequest webRequest = HttpWebRequest.Create(CoreMotivesRequestUri) as HttpWebRequest;
				webRequest.Proxy = null;
				webRequest.ContentType = "application/x-www-form-urlencoded";
				webRequest.UserAgent = UserAgent; // Page.Request.UserAgent;
				webRequest.Method = "POST";
				byte[] bytes = Encoding.ASCII.GetBytes(Parameters);
				webRequest.ContentLength = bytes.Length;
				using (Stream postStream = webRequest.GetRequestStream())
				{
					postStream.Write(bytes, 0, bytes.Length);
				}
			}
			catch (Exception ex)
			{
				SPSecurity.RunWithElevatedPrivileges(
				  delegate()
				  {
					  //Write to sharepoint trace this code works for SP2007, 
					  // for SP2010, trace log code can be found at http://msdn.microsoft.com/en-us/library/aa979522(v=office.14).aspx
					  TraceProvider.RegisterTraceProvider();
					  TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), Assembly.GetExecutingAssembly().FullName, "CoreMotivesTracking", "Web Part", ex.Message + " :: " + ex.StackTrace);
					  TraceProvider.UnregisterTraceProvider();
				  }
				);
			}


		}

	}
}
